<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class mgamescore extends MY_Model {

    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );
    public $mytable = "game_score";
    public $primaryKey = "game_id";
    public $resCode = "GAME_SCORE";

    function __construct() {
        parent::__construct();
    }

    function field() {
		$fieldData = array();
		$fieldData['game_id'] = 0;
		$fieldData['use_id'] = 0;
		$fieldData['gscore_score'] = 0;
		$fieldData['gscore_time_update'] = 0;
		$fieldData['gscore_ip'] = '';
		$fieldData['gscore_rank'] = 0;
		return $fieldData;
    }
	
	function save_score($game_id = 0, $user_id = 0, $score = 0){
		if($user_id ==0) $user_id = $this->muser->use_id;
		if($game_id == 0 || $user_id == 0 || $score == 0)
			return false;
		$check = $this->get(array(
			'game_id'=>$game_id, 
			'use_id'=>$this->muser->use_id));
		if($check){
			if($score > $check->gscore_score){
				$arr_update= array();
				$arr_update['gscore_score'] = $score;
				$arr_update['gscore_time_update'] = time();
				$arr_update['gscore_ip'] = $this->input->ip_address();
				$this->db->where('use_id', $user_id);
				$this->update($check->game_id, 'game_id',$arr_update);
				return true;
			}
		}
		else {
			$this->insert(array(
				'game_id' =>$game_id,
				'use_id' =>$user_id,
				'gscore_score' =>$score,
				'gscore_time_update' =>time(),
				'gscore_ip' =>$this->input->ip_address(),
				'gscore_rank' => 0,
			));
			return true;
		}
		return false;
	}
	
	function get_top($top = 3, $game_id = 0, $start_limit = 0){
		$this->db->where('gscore_rank >',0);
		$this->db->limit($top, $start_limit);
		$this->db->order_by('gscore_rank asc');
		$this->db->join('user as u','u.use_id = game_score.use_id');
		return $this->gets($game_id, 'game_id');
	}
}

?>